package com.jack.leetcode.linkedlist;

public class 两两交换链表中的节点 {

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        ListNode result = swapPairs(head);
        while (result != null) {
            System.out.print(result.val + ",");
            result = result.next;
        }
    }

    public static ListNode swapPairs(ListNode head) {
        ListNode result = new ListNode(0);
        ListNode r = result;
        result.next = head;
        ListNode p = result.next;
        while (p != null) {
            ListNode q = p.next;
            if (q != null) {
                p.next = q.next;
                q.next = p;
                r.next = q;
            }
            r = p;
            p = p.next;
        }
        return result.next;
    }
}
